<template>
	<scroll-view scroll-y="true" class="shoppingCart">
		<view class="main" v-if="info.length > 0" v-for="(storeItem,index) in info" :key="index">
			<view class="top">
				<view class="left" @click="jump('store')">
					<image :src="storeItem.merchant_icon" mode="aspectFill"></image>
					<text>{{storeItem.merchant_name}}</text>
				</view>
				<view class="right" @click="getedit()">
					<image :src="obtainImgUrl('icon/icon35.png')" mode="aspectFill"></image>
					<text>{{isedit?'完成':'编辑'}}</text>
				</view>
			</view>

			<uni-swipe-action v-for="(item,index2) in storeItem.productList" :key="index2">
				<uni-swipe-action-item :options="options" @click="delItem(item.id)" @change="change">
					<view class='cont'>
						<view class="left">
							<view :class="selList[item.id]?'sel':'nosel'" @click="selProduct(item.id)"></view>
							<image :src="item.product_img" mode="aspectFill" @click="jump(item.jumpType, item.jumpLink)"></image>
						</view>
						<view class="right">
							<text @click="jump(item.jumpType, item.jumpLink)">{{item.product_name}}</text>
							<text v-if="item.sku_name != ''" @click="jump(item.jumpType, item.jumpLink)">{{item.sku_name}}</text>
							<text class="price" @click="jump(item.jumpType, item.jumpLink)">{{item.price > 0 ? '￥'+item.price : ''}}{{item.price > 0 && item.point_exchange > 0 ? ' + ' : ''}}{{item.point_exchange > 0 ? item.point_exchange+'豆力' : ''}}</text>
							<view class="uni-numbox">
								<view class="uni-numbox-minus" :class="cartNumList[item.id].disableSubtract ? '' : 'uni-numbox-disabled'" @click="_calcValue('subtract', item.id)">-</view>  
								<input class="uni-numbox-value" type="number" :value="cartNumList[item.id].number" @blur="_onBlur" :data-id="item.id">  
								<view class="uni-numbox-plus" :class="cartNumList[item.id].disableAdd ? '' : 'uni-numbox-disabled'" @click="_calcValue('add', item.id)">+</view>
							</view>  
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
			<view class="bottom">
				<view class="left" @click="allSelFun()">
					<view :class="allsel?'sel':'nosel'" ></view>
					<text>全选</text>
				</view>
				<view class="right">
					<view v-if="isedit" class="del" @click="delAll()">
						删除
					</view>
					<view v-if="!isedit" class="text">
						<view class="all">
							<text>合计</text>
							<text>{{selTotalMoney == 0 && selTotalPoint == 0 ? '0' : ''}}{{selTotalMoney > 0 ? '￥'+selTotalMoney : ''}}{{selTotalMoney > 0 && selTotalPoint > 0 ? ' + ' : ''}}{{selTotalPoint > 0 ? selTotalPoint+'豆力' : ''}}</text>
						</view>
						<view class="freight">不含运费</view>
					</view>
					<text v-if="!isedit" class="pay" @click="confirmOrder()">结算({{selTotalNum}})</text>
				</view>
			</view>

		</view>
		<view v-if="info.length == 0" class="noshoppingCart">
			<image :src="obtainImgUrl('icon/nocar.png')" mode="aspectFill"></image>
			<text>
				暂未有商品加入购物车～
			</text>
		</view>
	</scroll-view> 

</template>

<script>
	import serve from '../../static/request.js';
	import storage from '../../static/appkey.js';
	import common from '../../static/jump.js';
	export default {
		data() {
			return {
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#EB5938',
						color: "#ffffff"
					}
				}],
				list: [{},{},{},{}],
				allsel: false,
				isedit: false,
				
				info: {},
				cartNumList: [],
				selList: [],
				selTotalNum: 0,
				selTotalMoney : 0,
				selTotalPoint : 0,
			}
		},
		methods: {
			delItem(cartId) {
				var self = this;
				let sku_id = self.cartNumList[cartId].sku_id;
				uni.showModal({
				    title: '提示',
				    content: '您确定删除该产品吗',
				    success: function (res) {
				        if (res.confirm) {
				            serve.request({
								url: '/member/cart-item/delete-ids',
								data:{
									'sku_ids':sku_id,
								}
							}).then(res => {
								uni.showToast({
									title:res.message,
								});
								if(res.code == 200) {
									let storeKey = self.cartNumList[cartId].store_key;
									let cartKey = self.cartNumList[cartId].cart_key;
									if(self.info[storeKey].productList.length == 1) {
										self.info.splice(storeKey, 1);
									} else {
										self.info[storeKey].productList.splice(cartKey, 1);
									}
									self.cartNumList[cartId] = [];
									self.$forceUpdate();
									self.totalSelFun();
								} 
							});
				        } 
				    }
				});
			},
			delAll(){
				var self = this;
				if(self.selTotalNum == 0) {
					uni.showToast({
						title: "请选择要删除的产品",
						icon: 'none'
					});
					return ;
				}
				let skuIds = '';
				let delSkuId = [];
				self.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key) => {
						if(self.selList[item.id]) {
							skuIds += item.sku_id + ',';
							delSkuId[item.id] = item.id;
						} 
					});
				});
				uni.showModal({
				    title: '提示',
				    content: '您确定删除选择的产品吗',
				    success: function (res) {
				        if (res.confirm) {
				            serve.request({
								url: '/member/cart-item/delete-ids',
								data:{
									'sku_ids':skuIds,
								}
							}).then(res => {
								uni.showToast({
									title:res.message,
								});
								if(res.code == 200) {
									delSkuId.forEach((cartId, key) => {
										let storeKey = self.cartNumList[cartId].store_key;
										let cartKey = self.cartNumList[cartId].cart_key;
										if(self.info[storeKey].productList.length == 1) {
											self.info.splice(storeKey, 1);
										} else {
											self.info[storeKey].productList.splice(cartKey, 1);
										}
										self.cartNumList[cartId] = [];
									});
									self.$forceUpdate();
									self.totalSelFun();
								} 
							});
				        } 
				    }
				});
			},
			confirmOrder() {
				var self = this;
				if(self.selTotalNum == 0) {
					uni.showToast({
						title: "请选择要提交订单的产品",
						icon: 'none'
					});
					return ;
				}
				let cartIds = '[';
				self.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key) => {
						if(self.selList[item.id]) {
							cartIds += item.id + ',';
						} 
					});
				});
				cartIds += '0]';
				self.jump('addOrder', 'type=cart&data='+cartIds);
			},
			selProduct(cartId) {
				if(this.selList[cartId]) {
					this.selList[cartId] = false;
				} else {
					this.selList[cartId] = true;
				}
				this.$forceUpdate();
				this.totalSelFun();
			},
			allSelFun() {
				if(this.allsel) {
					this.selList = [];
					this.allsel = false;
				} else {
					this.info.forEach((storeItem, key)=> {
						storeItem.productList.forEach((item,key) => {
							this.selList[item.id] = true;
						});
					});
					this.allsel = true;
				}
				this.$forceUpdate();
				this.totalSelFun();
			},
			totalSelFun() {
				let isAllSel = true;
				let totalMoney = 0;
				let totalPoint = 0;
				let totalNum = 0;
				console.info(this.info);
				this.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key) => {
						if(this.selList[item.id]) {
							totalNum ++;
							let productNum = this.cartNumList[item.id].number;
							totalMoney = parseFloat(Number(totalMoney) + Number(productNum * item.price));
							totalPoint = parseFloat(Number(totalPoint) + Number(productNum * item.point_exchange));
						} else {
							isAllSel = false;
						}
					});
				});
				this.allsel = isAllSel;
				this.selTotalMoney = totalMoney;
				this.selTotalPoint = totalPoint;
				this.selTotalNum = totalNum;
				this.$forceUpdate();
			},
			getedit() {
				this.isedit = !this.isedit
			},
			
			_calcValue(type, cartId) {
				let cartNumItem = this.cartNumList[cartId];
				let value = cartNumItem.number;  
				let step = cartNumItem.step;  
				let min = cartNumItem.min;
				let max = cartNumItem.max;
				let sku_id = cartNumItem.sku_id;
				if (type === 'subtract') {  
					value -= step  
				} else if (type === 'add') {  
					value = parseInt(Number(value) + Number(step))
				}  
				if (value < min || value > max) {  
					return  
				}  
				if(value == min) {
					this.cartNumList[cartId].disableSubtract = false;
				}
				if(value == max) {
					this.cartNumList[cartId].disableAdd = false;
				}
				serve.request({
					url: '/member/cart-item/update-num-new',
					data: {
						cart_id: cartId,
						sku_id: sku_id,
						num: value
					}
				}).then(res => {
					uni.showToast({
						title: res.message,
						icon : 'none'
					});
					if(res.code == 200) {
						// this.$set(this.cartNumList[cartId], 'number', value);
						this.cartNumList[cartId].number = value;
						this.$forceUpdate();
						console.log(1);
						this.totalSelFun();
					}
				});
			},
			_onBlur(event) {
				const cartId = event.target.dataset.id;
				let value = event.detail.value;
				let cartNumItem = this.cartNumList[cartId];
				let nowNum = cartNumItem.number;
				let min = cartNumItem.min;
				let max = cartNumItem.max;
				let sku_id = cartNumItem.sku_id;
				if (!value) {
					this.$forceUpdate();
					return  
				}  
				value = +value;
				if (value > max) {
					var self = this;
					uni.showToast({
						title: "当前产品最大购买数量为："+max,
						icon : 'none',
					});
					this.cartNumList[cartId].number = Number(nowNum);
					this.$forceUpdate();
					return ;
					// value = max;  
				} else if (value < min) { 
					uni.showToast({
						title: "当前产品最少购买数量为："+min,
						icon : 'none'
					});
					this.cartNumList[cartId].number = Number(nowNum);
					this.$forceUpdate();
					return ;
					// value = min  
				}  
				if(value == min) {
					this.cartNumList[cartId].disableSubtract = false;
				}
				if(value == max) {
					this.cartNumList[cartId].disableAdd = false;
				}
				serve.request({
					url: '/member/cart-item/update-num',
					data: {
						'sku_id': sku_id,
						num: value
					}
				}).then(res => {
					uni.showToast({
						title: res.message,
						icon : 'none'
					});
					if(res.code == 200) {
						this.cartNumList[cartId].number = Number(value);
						this.$forceUpdate();
					}
				});
				
			},
			getInfo() {
				serve.request({
					url: '/member/cart-item/new-index',
					data: {}
				}).then(res => {
					this.info = res.data;
					if(this.info.length > 0) {
						this.info.forEach((item, key) => {
							item.productList.forEach((cartItem, cartrKey) => {
								this.cartNumList[cartItem.id] = {
									'store_key' : key,
									'cart_key' : cartrKey,
									'sku_id' : cartItem.sku_id,
									'number' : cartItem.number,
									'disableSubtract': (cartItem.number == cartItem.min_buy ? true : false),
									'min' : cartItem.min_buy,
									'max' : cartItem.sku_stock,
									'step': cartItem.min_buy,
									'disableAdd': (cartItem.number == cartItem.sku_stock ? true : false),
								};
							});
						});
					}
					console.info(this.info.length);
					this.$forceUpdate();
				});
			},
			obtainImgUrl(imgUrl) {
				return serve.imgUrl()+imgUrl;
			},
			jump(jump_type, jump_link){
				common.jump(jump_type, jump_link);
			},
		},
		onLoad() {
			if(uni.getStorageSync('access-token') == '') {
				this.jump('login');
				return ;
			}
			this.getInfo();
		},
		onPullDownRefresh() {
			console.log('refresh');
			this.getInfo();
		}
	}
</script>

<style scoped lang="scss">
	@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
		    .main {
		        // padding-bottom: 224upx !important;
				.bottom{
					padding-bottom: 12px !important;
				}
		    }
		}
	.shoppingCart {
		height: 100vh;
        padding-bottom: 224upx !important;
        .noshoppingCart{
			width: 100%;
			min-height: 80vh;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			image{
				width: 128upx;
				height: 116upx;
			}
			text{
				font-size:28upx;
				color:rgba(204,204,204,1);
				margin-top: 38upx;
			};
		}
		.main {
			width: 100%;
			// padding-bottom: 200upx;

			.top {
				display: flex;
				padding: 33upx 30upx;
				box-sizing: border-box;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1upx rgba(235, 236, 240, 1) solid;

				.left {
					font-size: 32upx;
					display: flex;
					align-items: center;

					image {
						width: 35upx;
						height: 33upx;
						margin-right: 13upx;
					}

					text {
						position: relative;
						padding-right: 30upx;
					}

					text::after {
						position: absolute;
						right: 0upx;
						top: 17upx;
						content: '';
						border: 1upx solid rgba(57, 72, 107, 1);
						border-width: 0 3upx 3upx 0;
						padding: 6upx;
						transform: rotate(-45deg);
						-webkit-transform: rotate(-45deg);

					}
				}

				.right {
					font-size: 32upx;
					display: flex;
					align-items: center;

					image {
						width: 27upx;
						height: 33upx;
						margin-right: 20upx;
					}

				}
			}

			.cont {
				width: 100%;
				display: flex;
				align-items: center;
				box-sizing: border-box;
				padding: 40upx 30upx;
				border-bottom: 1upx #EBECF0 solid;

				.left {
					display: flex;
					align-items: center;

					image {
						width: 170upx;
						height: 170upx;
						margin-left: 20upx;
					}

					.sel {
						background-image: url(http://app.shanhaiyouyu.com/attachment/xcx/icon/icon37.png);
						background-repeat: no-repeat;
						width: 40upx;
						height: 40upx;
						background-size: 100%;
					}

					.nosel {
						width: 36upx;
						height: 36upx;
						border: 1upx solid rgba(60, 72, 104, 1);
						border-radius: 50%;
					}
				}

				.right {
					width: 440upx;
					height: 100%;
					position: relative;
					display: flex;
					flex-direction: column;
					justify-content: center;
					margin-left: 20upx;

					// .uni-numbox {
					// 	display: flex;
					// 	align-items: center;
					// 	position: absolute;
					// 	height: 60upx;
					// 	background: rgba(255, 255, 255, 1);
					// 	border: 1upx solid rgba(60, 72, 104, 0.1);
					// 	border-radius: 32upx;
					// 	overflow: hidden;
					// 	bottom: 0upx;
					// 	right: 0upx;
					// }
					
					.uni-numbox {
						display: flex;  
						flex-direction: row;  
						align-items: center;
						position: absolute;
						justify-content: flex-start;  
						background: rgba(255, 255, 255, 1);
						border: 1upx solid rgba(60, 72, 104, 0.1);
						border-radius: 32upx;
						height: 60upx;  
						overflow: hidden;
						bottom: 0upx;
						right: 0upx;
					}  
								
					.uni-numbox-minus,  
					.uni-numbox-plus {  
						margin: 0;  
						background-color: #FFFFFF;  
						width: 70upx;  
						height: 100%;  
						line-height: 60upx;  
						text-align: center;  
						color: #555555;  
					}  
								
					.uni-numbox-minus {  
						// border: 1upx solid #cccccc;  
						border-right: none;  
						// border-top-left-radius: 32upx;  
						// border-bottom-left-radius: 32upx;  
					}  
								
					.uni-numbox-plus {  
						// border: 2upx solid #cccccc;  
						border-left: none;  
						// border-top-right-radius: 6upx;  
						// border-bottom-right-radius: 6upx;  
					}  
								
					.uni-numbox-value {  
						border: 1upx solid rgba(60,72,104,0.06);  
						background-color: #ffffff;  
						width: 80upx;  
						height: 100%;  
						text-align: center;  
					}  
								
					.uni-numbox-disabled {  
						color: #c0c0c0;  
					} 

					text:nth-child(1) {
						font-size: 32upx;
						font-weight: bold;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					text:nth-child(2) {
						font-size: 24upx;
						color: rgba(60, 72, 104, 0.5);
						padding: 26upx 0upx;
						opacity: 0.5;
					}
                    .price {
						font-size: 24upx;
						color: rgba(255, 198, 0, 1) !important;
					}
				}
			}

			.bottom {
				border-top: 1upx #EBECF0 solid;
				padding-bottom: env(safe-area-inset-bottom);
				position: fixed;
				bottom: 0upx;
				background: #FFFFFF;
				box-sizing: border-box;
				padding-left: 30upx;
				display: flex;
				align-items: center;
				width: 100%;
				height: (100 + env(safe-area-inset-bottom))upx;
				box-shadow: 0px 1upx 0px 0px rgba(235, 236, 240, 1);
				justify-content: space-between;

				.left {
					display: flex;
					align-items: center;
					font-size: 28upx;

					.sel {
						background-image: url(http://app.shanhaiyouyu.com/attachment/xcx/icon/icon37.png);
						background-repeat: no-repeat;
						width: 40upx;
						height: 40upx;
						background-size: 100%;
						margin-right: 20upx;
					}

					.nosel {
						width: 35upx;
						height: 35upx;
						border: 1upx solid rgba(60, 72, 104, 1);
						border-radius: 50%;
						margin-right: 20upx;
					}
				}

				.right {
					display: flex;
					height: 100%;

					.del {
						width: 240upx;
						height: 72upx;
						background: rgba(245, 245, 245, 1);
						border-radius: 36upx;
						text-align: center;
						margin-top: 17upx;
						margin-right: 70upx;
						text-align: center;
						line-height: 72upx;
						font-size: 28upx;
					}

					.text {
						display: flex;
						justify-content: center;
						align-items: flex-end;
						padding-right: 15upx;
						flex-direction: column;

						.all {
							font-size: 20upx;
							color: rgba(60, 72, 104, 0.5);

							text:last-child {
								margin-left: 10upx;
								font-size: 28upx;
								font-weight: bold;
								color: rgba(255, 198, 0, 1);
							}
						}

						.freight {
							font-size: 20upx;
							color: rgba(60, 72, 104, 0.5);
						}
					}

					.pay {
						width: 240upx;
						height: 100%;
						background: rgba(235, 89, 56, 1);
						text-align: center;
						line-height: 100upx;
						font-size: 28upx;
						color: #FFFFFF;
						font-weight: bold;
					}
				}
			}

		}
	}
</style>
